<?php namespace App\Controllers\Admin;

/**
 * Created by PhpStorm.
 * User: joe
 * Date: 18-9-21
 * Time: 上午10:37
 */

use \App\Controllers\Application;
use \App\Libraries\Datatable;

class Question extends Application {

    protected $question;

    public function __construct(...$params) {
        parent::__construct(...$params);

        if (!$this->user) {
            $this->showError("用户尚未登录，请登录后重新打开。", site_url(''));
        }
        $this->question = new \App\Models\QuestionModel();
    }

    public function index() {
        $this->render('admin/question/list', '试题管理');
    }

    public function table($deleted = 0) {
        $table = $this->request->getGet();
        $users = new Datatable('question');

        if (isset($table['search']) && $table['search'] != "") {
            $users->like('question.title', $table['search']);
        }

        if (isset($table['sort'])) {
            $users->orderBy($table['sort'], $table['order']);
        }

        if (isset($table['limit'])) {
            $users->limit($table['limit'], $table['offset']);
        }

        $usersList = $users->select('question.id,question.title,level,category.name as categoryName,types.name as typeName')
                           ->join('category', 'category.id=question.category', 'left')
                           ->join('types', 'question.type=types.id', 'left')
                           ->where('deleted', $deleted)
                           ->json();

        echo $usersList;
    }

    public function add($id = 0) {
        if ($id) {
            $this->data['question'] = $this->question->find($id);
        }
        $category = new \App\Models\CategoryModel();
        $this->data['categories'] = $category->findAll();
        $type = new \App\Models\TypesModel();
        $this->data['types'] = $type->findAll();

        $this->render('admin/question/add', '增加/编辑试题');
    }

    public function save() {
        $option = $this->request->getPost('option');
        $answer = $this->request->getPost('answer');
        $question = [
            'id' => $this->request->getPost('id'),
            'category' => $this->request->getPost('category'),
            'type' => $this->request->getPost('type'),
            'title' => preg_replace('/\s/','',$this->request->getPost('title')),
            'level' => $this->request->getPost('level'),
            'analysis' => trim($this->request->getPost('analysis')),
            'date' => date('Y-m-d'),
        ];

        if (!$question['category']) {
            $this->showJson('您没有选择类别。', 'Error');
            return;
        }

        if (!strip_tags(trim($question['title']))) {
            $this->showJson('您没有输入题干。', 'Error');
            return;
        }

        if (in_array($question['type'], [1, 2, 3]) && !$answer) {
            $this->showJson('您没有选择答案。', 'Error');
            return;
        }

        $options = [];

        if (is_array($option) && is_array($answer)) {
            for ($i = 0; $i < count($option); $i++) {
                if (!$option[$i]) {
                    continue;
                }

                $options[] = [
                    't' => preg_replace('/\s/','',$option[$i]),
                    'a' => in_array($i, $answer) ? 't' : '',
                ];
            }
        } else {
            $options = $option;
        }

        $question['option'] = json_encode($options, JSON_UNESCAPED_UNICODE);

        $this->question->save($question);

        $this->showJson('保存成功', 'Success');
    }

    public function view($id = 0) {
        if (!$id) {
            return false;
        }
        $this->data['question'] = $this->question->select('question.*,types.name as type_name,category.name as category_name')
                                                 ->join("category", "category.id=question.category")
                                                 ->join("types", "types.id=question.type")
                                                 ->find($id);
        $this->render('admin/question/view', "试题详细内容");
    }

    public function delete() {
        $id = $this->request->getPost('id');
        $trash = $this->request->getPost('trash') ? true : false;

        if (!$id) {
            $this->showJson("未选择要删除的内容", 'Error');
        }

        $this->question->delete($id, $trash);
        $this->showJson($trash ? "已彻底删除" : "已放入回收站", "Success");
    }

    public function recover() {
        $id = $this->request->getPost('id');
        if (!$id) {
            $this->showJson("未选择要恢复的内容", 'Error');
        }

        $this->question->recover($id);
        $this->showJson("已恢复题目", "Success");
    }

    function emptyTrash() {
        $this->question->emptyTrash();
    }

    function import() {
        $this->question->import('./test.csv');
    }

}
